import Router from '../../modules/KoaMqRouter';
import Receiver from '../../modules/Receiver';

const prefix = 'dc';
const router = new Router();

const config = {
    ch1: {
        exchange: {
            name: 'dc-exchange',
            type: 'direct',
            opts: {
                durable: false,
            },
        },
        pattern: `${prefix}-node`,
        queue: {
            name: `${prefix}-node`,
            opts: {
                durable: false,
            },
        },
        consume: {
            opts: {},
        },
    },
};

function* dispatch(msg) {
    const log = this.app.log.getLogger('receiver');
    try {
        const fields = msg.fields;
        const content = msg.content.toString();

        log.info('[received] from channel[%s] exchange[%s]: %s',
            this.name, fields.exchange, content);

        const receiver = new Receiver(this.app);
        receiver.onMessage(JSON.parse(content));
    } catch (e) {
        log.info('[received] from channel[%s] error: %s', this.name, e);
    } finally {
        this.channel.ack(msg);
    }
}

for (const cfgKey of Object.keys(config)) {
    // 注册
    router.use(cfgKey, config[cfgKey], dispatch);
}

export {
    prefix,
    router,
};
